package com.ljd.cmn.Service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljd.cmn.Service.DictService;
import com.ljd.cmn.listener.DictListener;
import com.ljd.cmn.mapper.DictMapper;
import com.ljd.yygh.model.cmn.Dict;
import com.ljd.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper,Dict> implements DictService {

    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> getDictById(Long id) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId,id);
        List<Dict> dicts = this.baseMapper.selectList(wrapper);
        return dicts.stream().peek(dict -> dict.setHasChildren(hasChildren(dict.getId()))).collect(Collectors.toList());
    }

    @Override
    public void exportData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        List<Dict> dictList = this.baseMapper.selectList(null);
        List<DictEeVo> eeVoList = dictList.stream().map(dict -> {
            DictEeVo vo = new DictEeVo();
            BeanUtils.copyProperties(dict, vo);
            return vo;
        }).collect(Collectors.toList());
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(eeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        if(StringUtils.isEmpty(parentDictCode)) {
            LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value);
            Dict dict = this.baseMapper.selectOne(wrapper);
            if(null!=dict) {
                return dict.getName();
            }
        }else {
            Dict dict = this.getDictByDictCode(parentDictCode);
            if(null==dict){
                return "";
            }
            Long dictId = dict.getId();
            LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<Dict>().eq(Dict::getParentId,dictId)
                    .eq(Dict::getValue,value);
            Dict d = this.baseMapper.selectOne(wrapper);
            if(null!=d) {
                return d.getName();
            }
        }
        return "";
    }

    private Dict getDictByDictCode(String parentDictCode) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode,parentDictCode);
        return this.baseMapper.selectOne(wrapper);
    }

    private Boolean hasChildren(Long id) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId,id);
        Integer count = this.baseMapper.selectCount(wrapper);
        return count>0;
    }
}
